// 灰度的环境变量
const GRAY_ENVIRONMENT = '6.6';
// 是否清空
let IS_CLEAR = false;

// 灰度模式
const GRAY_MODE = 'delete' // add || delete

// 入口的接口地址
// 线上
// const ENTER_URL_CONFIG = [
//   'http://eip.foneshare.cn/fs-er-biz/gray/auth/system/listGrayEntryByGroupId/5c4f1e0abf1f0e6344b60f97' /* 服务通 */,
//   'http://eip.foneshare.cn/fs-er-biz/gray/auth/system/listGrayEntryByGroupId/5ae2e60d35978d6e1dcc9928' /* 设备通 */,
// ];
// const ROUTE_BASE_URL =
//   'http://eip.foneshare.cn/fs-er-biz/gray/auth/system/listGrayRouteByEntryId/';
// const ROUTE_UPDATE_URL =
//   'http://eip.foneshare.cn/fs-er-biz/gray/auth/system/updateGrayRoute';

// 测试环境
const ENTER_URL_CONFIG = [
  'http://172.31.101.246:48272/fs-er-biz/gray/auth/system/listGrayEntryByGroupId/5c46cb55385818a27c0a7dae' /* 服务通 */,
];
const ROUTE_BASE_URL =
  'http://172.31.101.246:48272/fs-er-biz/gray/auth/system/listGrayRouteByEntryId/';
const ROUTE_UPDATE_URL =
  'http://172.31.101.246:48272/fs-er-biz/gray/auth/system/updateGrayRoute';

// 获取请求头（身份验证信息）
function getHeaderParams() {
  const search = location.search.substr(1);
  const params = {};
  if (search) {
    for (
      let i = 0, array = search.split('&'), pair = null;
      i < array.length;
      i += 1
    ) {
      pair = array[i].split('=');
      if (pair[0]) {
        params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
      }
    }
  }
  params.portalUserName = encodeURIComponent(params.portalUserName);
  params['Content-Type'] = 'application/json;charset=UTF-8';
  return params;
}

const Api = function (url, params, method) {
  return fetch(url, {
    headers: getHeaderParams(),
    method: method || 'GET',
    body: JSON.stringify(params),
  })
    .then(res => res.json())
    .then(res => {
      if (!res.success) {
        return Promise.reject(res.errMessage);
      }
      return res;
    });
};

// 获取需要灰度的企业列表
function getGrayCompanyList() {
  var companyStr = prompt('请输入企业字符串（以逗号、分号或空格分隔）');
  var companyList =
    companyStr.replace(/["'“”‘’]+/g, '').match(/[^;；,， ]+/g) || [];
  if (companyList.length === 0) {
    IS_CLEAR = confirm(
      `没有输入企业，确定要清空${GRAY_ENVIRONMENT}灰度环境下所有已配置企业吗？`
    );
  }

  console.log(`共输入${companyList.length}个企业：`, companyList);
  return companyList;
}

// 合并企业，并过滤出重复企业
function mergeCompanyList(preList = [], pushList) {
  if (IS_CLEAR) return [[], []];

  const overLapList = [];
  let result = [...preList];
  
  if (GRAY_MODE === 'delete') {
    result = result.filter(company => !pushList.includes(company))
    return [result, overLapList];
  } 

  pushList.forEach(company => {
    result.includes(company) ? overLapList.push(company) : result.push(company);
  });

  return [result, overLapList];
}

// 获取所有入口地址
function getAllEnterList() {
  const result = [];
  const allPromise = ENTER_URL_CONFIG.map(url => {
    return Api(url).then(res => {
      result.push(...res.data);
    });
  });

  return Promise.all(allPromise).then(() => {
    console.log('所有配置入口列表：', result);
    return result;
  });
}

// 将灰度企业写入路由
function setGrayCompanyInRoute(routeData, entryData, grayCompanyList) {
  const [result, overLapList] = mergeCompanyList(
    routeData.grayEas || [],
    grayCompanyList
  );

  console.group(`---正在写入路由：${routeData.name}`);
  console.log('url：', routeData.url);
  console.log('原灰度企业列表：', routeData.grayEas);
  console.log('合并后企业列表：', result);
  console.log('已过滤重复企业列表：', overLapList);

  const params = Object.assign({}, routeData, {
    grayEas: result,
    grayEasStr: result.join(','),
  });
  return Api(ROUTE_UPDATE_URL, params, 'POST')
    .then(() => {
      console.log(`路由：${routeData.name}   灰度完成！`);
      console.groupEnd();
    })
    .catch(res => {
      console.error(`路由：${routeData.name}   灰度失败！`);
      console.error(res);
      console.groupEnd();
    });
}

// 将灰度企业写入入口
async function setGrayCompanyInEnter(entryData, grayCompanyList) {
  console.group(`--------------正在配置入口：${entryData.name}---------------`);
  const { data: routeList } = await Api(ROUTE_BASE_URL + entryData.id);
  for (const routeData of routeList) {
    if (routeData.url.includes(GRAY_ENVIRONMENT)) {
      await setGrayCompanyInRoute(routeData, entryData, grayCompanyList);
    } else {
      console.log(
        `---${routeData.name} 路由url不匹配 跳过`,
        routeData.url
      );
    }
  }
  console.groupEnd();
  return;
}

(async function main() {
  const grayCompanyList = getGrayCompanyList();
  // 不灰度企业，也不是清空，则直接中断
  if (grayCompanyList.length === 0 && !IS_CLEAR) return;

  const allEnterList = await getAllEnterList();

  for (const entryData of allEnterList) {
    await setGrayCompanyInEnter(entryData, grayCompanyList);
  }

  console.log('配置完成！');
})();
